package com.heking.qlyopensdkapp.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.heking.qlyopensdkapp.SharedPreferencesUtils;
import com.heking.qlyopensdkapp.QlyAccount;
import com.heking.qlyopensdkapp.R;
import com.heking.zplayer.qlyopen.Callback;
import com.heking.zplayer.qlyopen.IQlyPlayer;
import com.heking.zplayer.qlyopen.OnTalkListener;
import com.heking.zplayer.qlyopen.PlayError;
import com.heking.zplayer.qlyopen.PlayListener;
import com.heking.zplayer.qlyopen.QLYApi;
import com.heking.zplayer.qlyopen.QlyCameraAbility;
import com.heking.zplayer.qlyopen.QlyPlayer;
import com.heking.zplayer.qlyopen.QlyToken;
import com.heking.zplayer.qlyopen.QlyTokenParams;
import com.heking.zplayer.qlyopen.ZQlyOpenSdk;
import com.zhoug.permissions.ZPermissions;

import java.util.ArrayList;

import androidx.annotation.Nullable;

public class MainActivity extends BaseActivity {
    private static final String TAG = ">>>MainActivity";
    private static final String DEVICE_ID = "xxxxS_d4430e203fd4";
    private QlyPlayer mPlayer;
    private QlyCameraAbility mQlyCameraAbility;
    private Button mBtnInit;
    private Button mBtnGetMonitorToken;
    private FrameLayout mContainerPlayView;
    private ImageView mBtnPlay;

    private boolean retry = true;
    private TextView mTvError;
    private ProgressBar mProgressBar;
    private ImageView mBtnMute;
    private Button mBtnTalk;
    private Button mBtnToQlyPlayActivity;
    private Button mBtnToQlyPlayActivity1;

    @Override
    public void beforeLayout(@Nullable Bundle savedInstanceState) {

    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_main;
    }

    @Override
    protected void addListener() {

    }

    @Override
    protected void initView() {

    }


    @Override
    protected void findViews() {
        mBtnInit = findViewById(R.id.btn_init);
        mBtnGetMonitorToken = findViewById(R.id.btn_getMonitorToken);
        mContainerPlayView = findViewById(R.id.containerPlayView);
        mBtnPlay = findViewById(R.id.btn_play);
        mTvError = findViewById(R.id.tv_error);
        mProgressBar = findViewById(R.id.progressBar);
        mBtnMute = findViewById(R.id.btn_mute);
        mBtnTalk = findViewById(R.id.btn_talk);
        mBtnToQlyPlayActivity = findViewById(R.id.btn_toQlyPlayActivity);
        mBtnToQlyPlayActivity1 = findViewById(R.id.btn_toQlyPlayActivity1);
    }

    private void initSdk() {
        ZQlyOpenSdk.init(getApplication(), QlyAccount.appId, QlyAccount.privateKey, true);
    }

    @Override
    protected void onCreateEnd(@Nullable Bundle savedInstanceState) {
//        initSdk();

        mPlayer = new QlyPlayer(this);
        mPlayer.setPlayUrl(DEVICE_ID);
        mPlayer.setPlayViewGroup(mContainerPlayView);
        mPlayer.setPlayListener(new PlayListener() {
            @Override
            public void onPlayStatusChange(int state) {
                switch (state) {
                    case IQlyPlayer.STATE_IDLE:
                        showProgressBar(false);
                        setPlayButton(false);
                        Log.d(TAG, "onPlayStatusChange:IDLE");
                        break;
                    case IQlyPlayer.STATE_START:
                        showProgressBar(true);
                        setPlayButton(true);
                        Log.d(TAG, "onPlayStatusChange:开始播放");
                        break;
                    case IQlyPlayer.STATE_PREPARED:
                        Log.d(TAG, "onPlayStatusChange:资源准备好了");
                        break;
                    case IQlyPlayer.STATE_PLAYING:
                        showProgressBar(false);
                        setPlayButton(true);
                        Log.d(TAG, "onPlayStatusChange:正在播放");
                        break;
                    case IQlyPlayer.STATE_PAUSE:
                        showProgressBar(false);
                        setPlayButton(false);
                        Log.d(TAG, "onPlayStatusChange:暂停播放");
                        break;
                    case IQlyPlayer.STATE_ENDED:
                        showProgressBar(false);
                        setPlayButton(false);
                        Log.d(TAG, "onPlayStatusChange:播放完成了");
                        break;

                }
            }

            @Override
            public void onPlayError(int code, String error) {
                if (retry && code == PlayError.TOKEN_EXPIRE) {
                    Log.e(TAG, "token 过期 重新获取");
                    retry = false;
                    getOpenPlatformToken(new Callback<QlyToken>() {
                        @Override
                        public void onSuccess(QlyToken qlyToken) {
                            hideError();
                            mPlayer.startPlay();
                        }

                        @Override
                        public void onError(String error) {
                            showError(error);
                            setPlayButton(false);
                        }
                    });
                } else {
                    showError(error);
                    setPlayButton(false);
                }

            }
        });
        mPlayer.setOnTalkListener(new OnTalkListener() {
            @Override
            public void onTalkCallback(int status, String error) {
                toast(error);
            }
        });
        mPlayer.setOnCameraAbilityChange(new Callback<QlyCameraAbility>() {
            @Override
            public void onSuccess(QlyCameraAbility cameraAbility) {
                mQlyCameraAbility = cameraAbility;
                if (mQlyCameraAbility != null) {

                }
            }

            @Override
            public void onError(String error) {

            }
        });
        mBtnInit.setOnClickListener(v -> {
            initSdk();
        });
        mBtnGetMonitorToken.setOnClickListener(v -> {
            getOpenPlatformToken(null);
        });

        mBtnPlay.setOnClickListener(v -> {
            retry = true;
            hideError();
            if (mPlayer.isPlaying()) {
                setPlayButton(false);
                mPlayer.stopPlay();
            } else {
                setPlayButton(true);
                mPlayer.startPlay();
            }
        });

        mBtnMute.setOnClickListener(v -> {
            boolean mute = !mPlayer.isMute();
            mPlayer.setMute(mute);
            mBtnMute.setImageResource(mute ? R.drawable.icon_mute_true : R.drawable.icon_mute_false);
        });
        mBtnMute.setImageResource(mPlayer.isMute() ? R.drawable.icon_mute_true : R.drawable.icon_mute_false);

        mBtnTalk.setOnClickListener(v -> {
            if (mPlayer.isTalking()) {
                mBtnTalk.setText("对讲");
                mPlayer.stopVoiceTalk();
            } else {
                mBtnTalk.setText("请讲话");
                mPlayer.startVoiceTalk();
            }
        });
        mBtnToQlyPlayActivity.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, QlyPlayActivity.class);
            startActivity(intent);
        });
        mBtnToQlyPlayActivity1.setOnClickListener(v->{
            Intent intent = new Intent(MainActivity.this, QlyPlayActivity1.class);
            startActivity(intent);
        });

        /*ZPermissions.with(this)
                .setPermissions(Manifest.permission.INTERNET,
                        Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.REQUEST_INSTALL_PACKAGES,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_NETWORK_STATE
                )
                .setCallback(new ZPermissions.Callback() {
                    @Override
                    public void onRequestPermissionsResult(boolean success, ArrayList<String> granted, ArrayList<String> denied) {

                    }
                })
                .request();*/

    }

    private void getOpenPlatformToken(Callback<QlyToken> callback) {
        QlyToken qlyToken = SharedPreferencesUtils.getMonitorToken(DEVICE_ID);
        if (qlyToken != null && !qlyToken.isExpired()) {
            ZQlyOpenSdk.setOpenPlatformToken(qlyToken.getToken());
            if (callback != null) {
                callback.onSuccess(qlyToken);
            }
            return;
        }
        Log.d(TAG, "获取token");
        QlyTokenParams params = new QlyTokenParams();
        params.setAppId(QlyAccount.appId);
        params.setSecret(QlyAccount.secret);
        params.setOperatorType(ZQlyOpenSdk.TOKEN_OPERATOR_TYPE_CUSTOM);
        params.setTargetType(ZQlyOpenSdk.TARGET_TYPE_DEVICE);
        params.setTarget(DEVICE_ID);
        params.setAction(ZQlyOpenSdk.ACTION_WRITE);

        QLYApi.getOpenPlatformToken(params, new Callback<QlyToken>() {
            @Override
            public void onSuccess(QlyToken qlyToken) {
                logAndToastD(TAG, "获取设备token成功");
                SharedPreferencesUtils.setMonitorToken(params.getTarget(), qlyToken);
                ZQlyOpenSdk.setOpenPlatformToken(qlyToken.getToken());
                if (callback != null) {
                    callback.onSuccess(qlyToken);
                }
            }

            @Override
            public void onError(String error) {
                logAndToastE(TAG, "获取设备token失败:" + error);
                if (callback != null) {
                    callback.onError(error);
                }
            }
        });
    }

    private void showError(String error) {
        if (mTvError != null) {
            mTvError.setText(error);
            mTvError.setVisibility(View.VISIBLE);
        }
    }

    private void hideError() {
        if (mTvError != null) {
            mTvError.setVisibility(View.GONE);
        }
    }

    private void showProgressBar(boolean show) {
        if (mProgressBar != null) {
            mProgressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        }
    }

    private void setPlayButton(boolean play) {
        if (mBtnPlay != null) {
            mBtnPlay.setImageResource(play ? R.drawable.icon_play_start : R.drawable.icon_play_stop);
        }
    }
}